package baiqitun.stupro.common.service.support;

import baiqitun.stupro.common.entity.Entity;
import baiqitun.stupro.common.exception.support.ExistedException;
import baiqitun.stupro.common.exception.support.NotFoundException;
import baiqitun.stupro.common.service.MyService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;

/**
 * 系统业务类公共实现
 * @author kedaji
 * @param <M> 继承自Mybatis Plus的BaseMapper
 * @param <T> 继承自系统的Entity
 */
public class MyServiceImpl<M extends BaseMapper<T>, T extends Entity> extends ServiceImpl<M, T> implements MyService<T> {

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeById(String id, String updateBy) {
        UpdateWrapper<T> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id).set("update_by", updateBy);
        update(updateWrapper);
        return super.removeById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeByIds(Collection<? extends String> idList, String updateBy) {
        for (String id: idList){
            removeById(id, updateBy);
        }
        return true;
    }

    @Transactional(readOnly = true, rollbackFor = Exception.class)
    @Override
    public void checkNotFound(String id, NotFoundException e) {
        T entity = getById(id);
        if (entity == null){
            throw e.put("id", id);
        }
    }

    @Transactional(readOnly = true, rollbackFor = Exception.class)
    @Override
    public void checkExisted(String id, ExistedException e) {
        T entity = getById(id);
        if (entity != null){
            throw e.put("id", id);
        }
    }

    @Transactional(readOnly = true, rollbackFor = Exception.class)
    @Override
    public T getExistedEntity(String id, NotFoundException e) {
        T entity = getById(id);
        if (entity == null){
            throw e.put("id", id);
        }
        return entity;
    }
}
